import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { User } from './entities/user.entity';
import { PageResultDto } from 'src/common/dto';
import { Role } from '../role/entities/role.entity';
import { Dept } from '../dept/entities/dept.entity';
import { Brackets } from 'typeorm';
import { isEmptyStr } from 'src/common/utils/common';
@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>
  ) {}
  create(createUserDto: CreateUserDto) {
    return 'This action adds a new user';
  }

  // findAll() {
  //   return `This action returns all user`;
  // }

  async findAll(query:any, tenantId:string): Promise<PageResultDto<any>> {
    // console.log(current, size);
    let users = await this.usersRepository.createQueryBuilder('user')
      .leftJoinAndSelect('user.Role', 'Role')
      .where('user.deleted = :deleted', { deleted: 0 })
      .andWhere('user.tenantId = :tenantId', { tenantId: tenantId })
      .andWhere(new Brackets(qb => {
        if(!isEmptyStr(query.userName)){
          qb.where('user.userName LIKE :userName', { userName: `%${query.userName}%` });
        }
        if(!isEmptyStr(query.realName)){
          qb.andWhere('user.realName LIKE :realName', { realName: `%${query.realName}%` });
        }
      }))
      .select('user.Id', 'Id')
      .addSelect('user.userName', 'userName')
      .addSelect('user.phone', 'phone')
      .addSelect('user.realName', 'realName')
      .addSelect('user.status', 'status')      
      .addSelect('Role.Id', 'roleId') // 只选择 role 的 id
      .addSelect('Role.name', 'roleName') // 只选择 role 的 id
      .skip((query.current - 1) * query.size)
      .take(query.size)
      .getRawMany();
    
    let result = new PageResultDto<any>();
    result.data = users;
    result.total = await this.usersRepository.count();
    result.pageNum = query.current;
    result.pageSize = query.size;
    return result;
  }

  async findOne(id: string):  Promise<[boolean, User]> {
    let user = await this.usersRepository.findOne({ where: { Id: id } });
    console.log(user.password)
    if (!user) {
      return [false, new User()];
    }
    // console.log('查询用户成功', user);
    return [true, user];
  }

  async findOneByUsername(username: string): Promise<[boolean, User]> {
    let user = await this.usersRepository.findOne({ where: { userName: username }, relations: ['Role'] });
    if (!user) {
      return [false, new User()];
    }
    console.log('查询用户成功', user);
    return [true, user];
  }

  async update(updateUserDto: CreateUserDto):  Promise<[boolean, string]> {
    let user = await this.usersRepository.findOne({ where: { Id: updateUserDto.Id }, relations: ['Role'] });
    if (!user) {
      return [false, "更新失败，用户不存在"];
    }
    // 更新用户信息
    user = this.usersRepository.create(updateUserDto);
    const role = new Role();
    role.Id = updateUserDto.roleId;
    const dept = new Dept();
    dept.Id = updateUserDto.deptId;
    await this.usersRepository.update(user.Id, {
      phone: user.phone,
      status: user.status,
      realName: user.realName,
      updateBy: user.updateBy,
      Role: role,
      Dept: dept,
    });
    return [true, "更新成功"];
  }

  async remove(id: string) {
    const existUser = await this.usersRepository.findOne({ where: { Id: id } });
    if (!existUser) {
      return [false, `用户不存在`];
    }
    await this.usersRepository.update(id, { deleted: 1 });
    // console.log('用户删除成功');
    return [true, '用户删除成功'];
    // return `This action removes a #${id} user`;
  }
  async register(createUserDto: CreateUserDto) {
    try {
      // 检查必填字段
      if (!createUserDto.userName || !createUserDto.password) {
        throw new Error('用户名和密码是必填字段');
      }
    } catch (error) {
      console.error('注册失败:', error.message); 
    }
    // 这里可以添加注册逻辑，比如保存用户到数据库
    // console.log('注册用户', createUserDto);
    let username = createUserDto.userName;
    const existUser = await this.usersRepository.findOne({ where: { userName: username } });
    console.log(existUser);
    if (existUser) {
      console.log('用户已存在');
      return "用户已存在";
    } 

    const role = new Role();
    const dept = new Dept();

    if(createUserDto.deptId == null || createUserDto.deptId == undefined){
      
    }else{
      
      dept.Id = createUserDto.deptId;
    }

    if(createUserDto.roleId == null || createUserDto.roleId == undefined){
      
    }else{
      
      role.Id = createUserDto.roleId;
    }
    
    const user = this.usersRepository.create(createUserDto);
    // console.log(user);
    user.Role = role;
    user.Dept = dept;
    user.status = 1; // 默认启用状态
    console.log(user);
    await this.usersRepository.insert(user);
    
    console.log('用户注册成功');
    return user;
  }
}
